/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cestum.cave.presenter.wave.utils {
import com.hurlant.math.BigInteger;

import flash.utils.ByteArray;

import org.cestum.cave.presenter.wave.HashedVersion;
import org.cestum.cave.presenter.wave.HashedVersionFactory;
import org.waveprotocol.wave.model.id.IdURIEncoderDecoder;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.util.URLEncoderDecoderBasedPercentEncoderDecoder;

/**
 * Utility class for creating Hashed Versions, the "lightweight" base class can only
 * calculate the version 0 hash and is suitable for use in the client.
 *
 *
 *
 */
public class HashedVersionZeroFactoryImpl implements HashedVersionFactory {
	
	private var URI_CODEC:IdURIEncoderDecoder= new IdURIEncoderDecoder(
		new URLEncoderDecoderBasedPercentEncoderDecoder());
	
	/**
	 * Create a new HashedVersion for version 0 of the given wavelet.
	 * @param waveletName the name of wavelet.
	 * @throws IllegalArgumentException if a bad wavelet name is passed.
	 * @return new HashedVersion at version 0.
	 */
	
	public function createVersionZero(waveletName:WaveletName):HashedVersion {
		try {
			// Same encoding as used protobuf/CodedOutputSteam to serialize a String to byte[].
			// http://code.google.com/p/protobuf/source/browse/trunk/java/src/main/java/com/google/protobuf/CodedOutputStream.java
			
			var historyHash:ByteArray= URI_CODEC.waveletNameToURI(waveletName);
			return new HashedVersion(new BigInteger("0"), historyHash);
		} catch (e) {
			throw new Error("Bad wavelet name " + waveletName + e);
		}
		
		catch (e) {
			throw new Error("Bad wavelet name " + waveletName + e);
			
		}
		return null;
	}
	
	/** Explicitly fail for creating a hashed version with version not 0. */
	
	public function createUsingDelta(appliedDeltaBytes:ByteArray, hashedVersionAppliedAt:HashedVersion,
									 operationsApplied:int):HashedVersion {
		// For lightweight users of this Factory, don't depend on crypto code.
		throw new Error("This method is not supported here.");
	}
	
	
	public function create(version:BigInteger, historyHash:ByteArray):HashedVersion {
		return new HashedVersion(version, historyHash);
	}
}
}